package com.hotacorp.opencloud.userservice.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections4.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.hotacorp.opencloud.common.authcommon.SysUserBean;
import com.hotacorp.opencloud.common.commdata.Constants;
import com.hotacorp.opencloud.common.commdata.Result;
import com.hotacorp.opencloud.common.mybatisplus.PageData;
import com.hotacorp.opencloud.common.resourcecommon.validator.group.AddGroup;
import com.hotacorp.opencloud.common.resourcecommon.validator.group.UpdateGroup;
import com.hotacorp.opencloud.userservice.entity.SysUserEntity;
import com.hotacorp.opencloud.userservice.service.SysUserRoleService;
import com.hotacorp.opencloud.userservice.service.SysUserService;

import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;

/**
 * 用户信息表
 *
 * @author lwg
 * @email lwg@gmail.com
 * @date 2019-12-25 11:52:19
 */
@RestController
public class SysUserController extends AbstractController {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysUserRoleService sysUserRoleService;

    /**
     * 列表
     */
    @RequestMapping(value = "/sysuser/list", method = {RequestMethod.OPTIONS, RequestMethod.GET, RequestMethod.POST})
    @PreAuthorize("hasAuthority('userservice:sysuser:list')")
    public Result<?> list(@RequestParam Map<String, Object> params){
    	params.put("tenantid", getTenantid());
        PageData page = sysUserService.queryPage(params);

        return Result.succeed("succeed", page);
    }


    /**
     * 信息
     */
    @RequestMapping(value = "/sysuser/info/{id}", method = {RequestMethod.OPTIONS, RequestMethod.GET, RequestMethod.POST})
    @PreAuthorize("hasAuthority('userservice:sysuser:info')")
    public Result<?> info(@PathVariable("id") Long id){
		SysUserEntity sysUser = sysUserService.getById(id);
		if (sysUser != null) {
			sysUser.setPassword(null);
			List<Long> rrrr = sysUserRoleService.queryRoleIdList(id, getTenantid());
			sysUser.setRoleIdList(rrrr);
	        return Result.succeed("succeed", sysUser);
		} else {
			return Result.failed("没有找到用户");
		}
    }

	/**
	 * 修改登录用户密码
	 */
    @GetMapping("/sysuser/password")
	public Result<?> password(@RequestParam("password") String password, @RequestParam("newPassword") String newPassword){
		if (StringUtils.isEmpty(newPassword)) {
			return Result.failed("新密码不能为空");
		}
				
		//更新密码
		boolean flag = sysUserService.updatePassword(getUserId(), password, newPassword);
		if(!flag){
			return Result.failed("原密码不正确");
		}
		
		return Result.succeed();
	}

	/**
     * 保存
     */
    @RequestMapping(value = "/sysuser/save", method = {RequestMethod.OPTIONS, RequestMethod.POST})
    @PreAuthorize("hasAuthority('userservice:sysuser:save')")
    public Result<?> save(@RequestBody @Validated(AddGroup.class) SysUserEntity sysUser){
		sysUserService.saveUser(sysUser, getTenantid());

        return Result.succeed();
    }

    /**
     * 修改
     */
    @RequestMapping(value = "/sysuser/update", method = {RequestMethod.OPTIONS, RequestMethod.POST})
    @PreAuthorize("hasAuthority('userservice:sysuser:update')")
    public Result<?> update(@RequestBody @Validated(UpdateGroup.class) SysUserEntity sysUser){
		sysUserService.update(sysUser, getTenantid());

        return Result.succeed();
    }

    /**
     * 删除
     */
    @RequestMapping(value = "/sysuser/delete", method = {RequestMethod.OPTIONS, RequestMethod.POST})
    @PreAuthorize("hasAuthority('userservice:sysuser:delete')")
    public Result<?> delete(@RequestBody Long[] ids){
		sysUserService.removeByIds(Arrays.asList(ids), getTenantid());

        return Result.succeed();
    }
    
    /**
     * 当前登录用户信息
     */
    @RequestMapping(value = "/sysuser/info", method = {RequestMethod.OPTIONS, RequestMethod.GET})
    public Result<?> info(){
    	Map<String, String> data = new HashedMap<String, String>();
    	data.put("userId", String.valueOf(getUserId()));
    	data.put("userName", getNickname());
    	data.put("userName1", getUsername());
        return Result.succeed("成功", data);
    }
    
    
    @GetMapping(value = "/anon/usernamelogin", params = "username")
    @ApiOperation(value = "根据用户名查询用户")
    @ApiIgnore
    public Result<?> findByUsername(@RequestHeader(value=Constants.TENANT_ID_HEAD, required = true) Long tenantid, @RequestParam("username") String username) {
    	SysUserBean ddd = sysUserService.loadUserByUsername(tenantid, username);
    	if (ddd == null) {
    		return Result.failed("没有找到用户");
    	} else {
        	return Result.succeed("succeed", ddd);
		}
    }
    
    @GetMapping(value = "/anon/phonelogin", params = "phone")
    @ApiOperation(value = "根据手机号查询用户")
    @ApiIgnore
    public Result<?> findByMobile(@RequestHeader(value=Constants.TENANT_ID_HEAD, required = true) Long tenantid, @RequestParam("phone") String phone) {
    	SysUserBean ddd = sysUserService.loadUserByPhone(tenantid, phone);
    	if (ddd == null) {
    		return Result.failed("没有找到用户");
    	} else {
        	return Result.succeed("succeed", ddd);
		}
    }

}
